<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'get';
if($_SESSION['uid'] && $_RQ['op']=='get'){
	exi('','','core/account.siteinfo/');
}
//再次获取一次openid,如果还是失败就算了
if(!$_SESSION['openid'] && $_SESSION['os']!='windows' && $_SESSION['isauth_basecheck']!=1){
	$_SESSION['isauth_base']=0;
	$_SESSION['isauth_basecheck']=1;
}
if($_RQ['op']=='get'){
	$page=core_setting('site');
	set_html('title','登录');
	$operating=core_setting('operating');
	$return=array(
		'verify_code'=>$_AR['system']['verify_code']?true:false,
		'mobile_code'=>$_AR['system']['mobile_code']?true:false,
		'wechat_login'=>$_AR['system']['wechat_login']?true:false,
		'wechat_scan_login'=>$_AR['system']['wechat_scan_login']?true:false,
		'qq_login'=>$_AR['system']['qq_login']?true:false,
		'llogo'=>tomedia($page['llogo']),
		'name'=>$page['name'],
		'ico'=>$operating['logo'],
		'item'=>array()
	);
	$return['site']=core_setting('site');
	$return['operating']=$operating;
	if($return['wechat_scan_login']){
		//主站点没有绑定公众号
		$wechat=model('core/web')->get_manage_wechat();
		if(!$wechat || $wechat['type']!=4){
			$return['wechat_scan_login']=false;
		}
	}
	$return['site']=$page;
	$return['item']=array(
		'login_type'=>1,
	);
	if($_SESSION['container']!='wechat' && $_SESSION['container']!='wxapp'){
		$return['openlogin']=true;
	}
	$return['system']=$_AR['system'];
	$return['session_id']=session_id();
	set_html('header','common/header-cms');
	set_html('title','登录');
	exi($return);
}
if($_RQ['op']=='login'){
	$post=get_postdata();
	//校验登陆
	if($_AR['system']['verify_code']==1 && !check_image_code($post['code'])){
		exi('图片验证码错误！','error');
	}
	$member = array();
	if($post['login_type']==1){
		//账号密码登陆
		
		$name = trim($post['name']);
		pdo_delete('core_user_failed_login',array('lastupdate <'=>TIMESTAMP-900));
		$failed = pdo_get('core_user_failed_login', array('name' => $name));
		if ($failed['count'] >= 5){
			exi('输入密码错误次数超过5次，请在15分钟后再登录','error');
		}
		if(empty($name)) {
			exi('请输入要登录的用户名','error');
		}
		if(empty($post['password'])) {
			exi('请输入密码','error');
		}
		$record = pdo_get('core_users',array('name'=>$name),array('id','salt','password'));
		if(empty($record)){
			//找不到用户，尝试通过uc登陆
			$check=cfc('user')->uc_login($name,$post['password']);
			if(!$check){
				exi('账号不存在或密码错误！','error');
			}
			//登陆成功，创建用户
			$record=array();
			$record['id']=cfc('user')->create_user(array('name'=>$name,'password'=>$post['password']),false);
		}else{
			if(!check_password($post['password'],$record['salt'],$record['password'])){
				if (empty($failed)) {
					pdo_insert('core_user_failed_login', array( 'name' => $name, 'count' => '1', 'lastupdate' => TIMESTAMP));
				} else {
					pdo_update('core_user_failed_login', array('count' => $failed['count'] + 1, 'lastupdate' => TIMESTAMP), array('id' => $failed['id']));
				}
				exi('账号不存在或密码错误！','error');
			}
		}
	}else{
		//手机验证码登陆
		if(!$post['smscode'] || $post['smscode']!=$_SESSION['smscode']){
			exi('手机验证码错误！','error');
		}
		$record=pdo_get('core_users',array('mobile'=>$post['mobile']));
		if(!$record){
			exi('用户不存在！','error');
		}
	}
	
    $res=cfc('user')->login($record['id']);
	if(is_error($res)){
		exi($res['message'],'error');
	}
	$_SESSION['access']=array();
	//如果是超级管理员，检查是否配置云服务参数，如果尚未配置，引导前往配置。是否在安装过程中就初始化安装基础插件呢？否。增加一个初始化功能
	//如何判断是否有初始化？
	//如果增加初始化判断功能，是否会影响现有客户。
	if($_SESSION['isfounder']){
		$check=core_setting('cloud');
		if(!$check){
			//引导配置云服务参数
			exi('欢迎回来，管理员！系统检测到您尚未配置云服务参数，请前往配置，以便享受更多功能与服务！','','./index.php?core/cloud.profile/');
		}
		//清空缓存
		cache_delete('cloud_newversion');
		cache_delete('cloud_getapps');
		cache_delete('cloud_getnews');
		cache_delete('cloud_ads');
		cache_delete('plugin_getapps','jy_weishop');
		cache_delete('plugin_getlegaos','jy_weishop');
		cache_delete('plugin_gettpls','jy_weishop');
		cache_delete('authapps');
	}
	$url=model('core/user')->home_page();
	exi('登陆成功！','',manage_url($url,true));
}
if($_RQ['op']=='send_code'){
	if(!$_AR['system']['mobile_code'] || !$_AR['system']['mobile_mb']){
		exi('系统暂不支持手机号码登陆！','error');
	}
	$post=get_postdata();
	if($_AR['system']['verify_code']==1 && !check_image_code($post['code'])) {
		exi('图片验证码错误！','error');
	}
	$mobile=trim($post['mobile']);
	if(!$mobile){
		exi('手机号格式错误！','error');
	}
	$mobile="$mobile";
	if(strlen($mobile)!=11){
		exi('手机号不合法！','error');
	}
	$check=pdo_getcolumn('core_users',array('mobile'=>$mobile),'id');
	if(!$check){
		exi('该手机号用户不存在！请先注册！','error');
	}
	$_SESSION['smscode']=random(6,true);
	$res=cfc('jy_alisms')->send($mobile,array('code'=>$_SESSION['smscode']),$_AR['system']['mobile_mb']);
	if(is_error($res)){
		exi('短信发送失败！'.$res['message'],'error');
	}else{
		exi('success');
	}
}
if($_RQ['op']=='wechat_scan_login'){
	//微信一键登陆
	$post=get_postdata();
	if($post['openid']){
		$openid=cfc('tools')->base64_decode($post['openid'],BASE64_KEY);
	}else{
		$openid=$_SESSION['openid'];
	}
	if(!$openid){
		exi('暂不支持微信一键登录，联系管理员配置好公众号！','error');
	}
	$uniacid=pdo_getcolumn('core_open_user',array('open_id'=>'1003','open_uid'=>$openid),'uniacid');
	if(!$uniacid){
		$setting=core_setting('zhuce');
		if(!$setting['open']){
			exi('当前微信尚未绑定本站账号！系统自动注册失败:本站暂未开启注册！','error','core/user.login/');
		}
		do{
			$username='wechat_'.random(10,true);
			$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
		}while($check);
		$member=array('name'=>$username);
		$uniacid=cfc('user')->create_user($member);
		$user=array(
			'uniacid'=>$uniacid,
			'open_id'=>'1003',
			'open_uid'=>$openid,
		);
		pdo_insert('core_open_user',$user);
	}
	//登陆用户
	cfc('user')->login($uniacid);
	exi('登陆成功！','','./index.php');
}
//微信授权登陆
if($_RQ['op']=='sq_login'){
	if(!$_SESSION['openid']){
		exi('暂不支持微信一键登录，联系管理员配置好公众号！','error');
	}
	$openid=model('core/tools')->base64_encode($_SESSION['openid'],BASE64_KEY);
	model('core/jinyun_socket')->send2uid(array('openid'=>$openid),$_RQ['session_id']);
	exi('登陆成功！','','/home.welcome/');
}
if($_RQ['op']=='wechat_login'){
	if(!$_AR['system']['wechat_login']){
		exi('系统暂不支持微信登陆！','error','./index.php');
	}
	if($_RQ['step']=='local_back'){
		if(!$_RQ['code']){
			exi('授权登陆失败！','error','get');
		}
		$setting=core_setting('system');
		$api="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$setting['wechat_login_appid']}&secret={$setting['wechat_login_appsecret']}&code={$_RQ['code']}&grant_type=authorization_code";
		$result=file_get_contents($api);
		$result=json_decode($result,true);
		if($result['errcode']){
			exi($result['errmsg'],'error','get');
		}
		//获取openid后转至正常处理流程
		$_RQ['openid']=$result['openid'];
		$_RQ['step']='cloud_back';
	}
	if($_RQ['step']=='cloud_back'){
		if($_RQ['openid']){
			//获得openid，为用户登陆
			$openid=trim($_RQ['openid']);
			
			$uniacid=pdo_getcolumn('core_open_user',array('open_id'=>'1001','open_uid'=>$openid),'uniacid');
			if(!$uniacid){
				$setting=core_setting('zhuce');
				if(!$setting['open']){
					exi('当前微信尚未绑定本站账号！系统自动注册失败:本站暂未开启注册！','error','core/user.login/');
				}
				do{
					$username='wechat_'.random(10);
					$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
				}while($check);
				$member=array('name'=>$username);
				$uniacid=cfc('user')->create_user($member);
				$user=array(
					'uniacid'=>$uniacid,
					'open_id'=>'1001',
					'open_uid'=>$openid,
				);
				pdo_insert('core_open_user',$user);
			}
			//登陆用户
			cfc('user')->login($uniacid);
			$message='授权登陆成功！';
		}else{
			$message='授权登陆失败！';
		}
		//跳转首页
		$_SESSION['access']=array();
		exi($message,'','./index.php');
	}
	//微信授权登陆，先检查是否配置好微信授权登陆参数，如尚未配置，则通过云平台接口完成登陆，否则通过本地接口完成登陆
	$setting=core_setting('system');
	if($setting['wechat_login_appid'] && $setting['wechat_login_appsecret']){
		$back_url=urlencode(SITEROOT.'manage/index.php?plugin=core&action=user.login&op=wechat_login&step=local_back');
		$url="https://open.weixin.qq.com/connect/qrconnect?appid={$setting['wechat_login_appid']}&redirect_uri={$back_url}&response_type=code&scope=snsapi_login&state=state#wechat_redirect";
	}else{
		$back_url=SITEROOT.'manage/index.php?plugin=core&action=user.login&op=wechat_login&step=cloud_back';
		$url=cloud_request('cloud.login.wechat',array('back_url'=>$back_url));
	}
	exi('','',$url);
}
if($_RQ['op']=='qq_login'){
	if(!$_AR['system']['qq_login']){
		exi('系统暂不支持QQ登陆！','error','./index.php');
	}
	if($_RQ['step']=='local_back'){
		if(!$_RQ['code']){
			exi('授权登陆失败！','error','get');
		}
		$setting=core_setting('system');
		$back_url=urlencode(SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qq_login&step=local_back');
		$url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={$setting['qq_login_appid']}&client_secret={$setting['qq_login_appsecret']}&code={$_RQ['code']}&redirect_uri={$back_url}";
		$res=file_get_contents($url);
		$res=explode('&',$res);
		$result=array();
		foreach($res as $row){
			$row=explode('=',$row);
			$result[$row['0']]=$row['1'];
		}
		$url='https://graph.qq.com/oauth2.0/me?access_token='.$result['access_token'];
		$res=file_get_contents($url);
		$res=substr($res,9,-3);
		$res=json_decode($res,true);
		//获取openid后转至正常处理流程
		$_RQ['openid']=$res['openid'];
		$_RQ['step']='cloud_back';
	}
	if($_RQ['step']=='cloud_back'){
		if($_RQ['openid']){
			//获得openid，为用户登陆
			$openid=trim($_RQ['openid']);
			$uniacid=pdo_getcolumn('core_open_user',array('open_id'=>'1002','open_uid'=>$openid),'uniacid');
			if(!$uniacid){
				$setting=core_setting('zhuce');
				if(!$setting['open']){
					exi('当前QQ尚未绑定本站账号！系统自动注册失败:本站暂未开启注册！','error','./index.php');
				}
				do{
					$username='qq_'.random(10);
					$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
				}while($check);
				$member=array('name'=>$username);
				$uniacid=cfc('user')->create_user($member);
				$user=array(
					'uniacid'=>$uniacid,
					'open_id'=>'1002',
					'open_uid'=>$openid,
				);
				pdo_insert('core_open_user',$user);
			}
			//登陆用户
			cfc('user')->login($uniacid);
			//跳转首页
			$_SESSION['access']=array();
			exi('授权登陆成功！','','./index.php');
		}else{
			$_SESSION['access']=array();
			exi('授权登录失败！','','./index.php');
		}
		
	}
	//QQ授权登陆
	$setting=core_setting('system');
	if($setting['qq_login_appid'] && $setting['qq_login_appsecret']){
		$back_url=urlencode(SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qq_login&step=local_back');
		$url="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={$setting['qq_login_appid']}&redirect_uri={$back_url}&state=state";
	}else{
		$back_url=SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qq_login&step=cloud_back';
		$url=cloud_request('cloud.login.qq',array('back_url'=>$back_url));
	}
	exi('','',$url);
}
//腾讯云开放平台授权登陆
if($_RQ['op']=='qcloud_login'){
	if(!$_AR['system']['qcloud_login']){
		//exi('系统暂不支持腾讯云登陆！','error','./index.php');
	}
	if($_RQ['step']=='local_back'){
		if(!$_RQ['code']){
			exi('授权登陆失败！','error','get');
		}
		$setting=core_setting('qcloud');
		$nonce=rand(100000,999999);
		$timestamp=TIMESTAMP;
		$params=array(
			'Action'=>'GetUserAccessToken',
			'SecretId'=>$setting['appSecretId'],
			'userAuthCode'=>$_RQ['code'],
			'Nonce'=>$nonce,
			'Timestamp'=>$timestamp,
			'SignatureMethod'=>'HmacSHA256',
		);
		ksort($params);
		$query_string=http_build_query($params);
		$sign_string='GETopen.api.qcloud.com/v2/index.php?'.$query_string;
		$signature=urlencode(base64_encode(hash_hmac('sha256',$sign_string,$setting['appSecretKey'],true)));
		$url="https://open.api.qcloud.com/v2/index.php?{$query_string}&Signature={$signature}";
		$res=file_get_contents($url);
		$res=json_decode($res,true);
		if($res['code']){
			exi('获取用户信息失败！原因为：'.$res['message'],'error','get');
		}
		
		//获取openid后转至正常处理流程
		$_RQ['openid']=$res['data']['userOpenId'];
		$_RQ['step']='cloud_back';
	}
	if($_RQ['step']=='cloud_back'){
		if($_RQ['openid']){
			//获得openid，为用户登陆
			$openid=trim($_RQ['openid']);
			$uniacid=pdo_getcolumn('core_open_user',array('open_id'=>'1003','open_uid'=>$openid),'uniacid');
			if(!$uniacid){
				$setting=core_setting('zhuce');
				if(!$setting['open']){
					exi('当前用户尚未绑定本站账号！系统自动注册失败:本站暂未开启注册！','error','./index.php');
				}
				do{
					$username='qcloud_'.random(5,true);
					$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
				}while($check);
				$member=array('name'=>$username);
				$uniacid=cfc('user')->create_user($member);
				$user=array(
					'uniacid'=>$uniacid,
					'open_id'=>'1003',
					'open_uid'=>$openid,
				);
				pdo_insert('core_open_user',$user);
			}
			//登陆用户
			cfc('user')->login($uniacid);
			//跳转首页
			$_SESSION['access']=array();
			exi('授权登陆成功！','','./index.php');
		}else{
			$_SESSION['access']=array();
			exi('授权登录失败！','','./index.php');
		}
		
	}
	//腾讯云授权登陆
	$setting=core_setting('qcloud');
	if($setting['appid']){
		$back_url=urlencode(SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qcloud_login&step=local_back');
		$url="https://www.qcloud.com/open/authorize?scope=login&app_id={$setting['appid']}&redirect_url={$back_url}&state=state";
	}else{
		exi('参数为空，无法发起授权登陆，请联系网站管理员！','error');
		$back_url=SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qcloud_login&step=cloud_back';
		$url=cloud_request('cloud.login.qq',array('back_url'=>$back_url));
	}
	exi('','',$url);
}
//企业微信授权登陆
if($_RQ['op']=='wxwork_login'){
	exi('企业微信！暂不支持免登授权！','error');
	exi('','',$url);
}
if($_RQ['op']=='wxauth_check'){
	$fans=pdo_get('core_open_user',array('open_uid'=>$_SESSION['openid']));
	$return['fans']=pdo_get('core_users',array('id'=>$fans['uniacid']),array('nickname','avatar'));
	$return['session_id']=$_RQ['session_id'];
	$return['forward']=$_RQ['forward'];
	exi($return);
}
